package android.olsson.apk;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import android.olsson.apk.interfaces.IBeverage;
import android.olsson.apk.interfaces.IFileHandler;
import android.os.Environment;
import android.util.Log;

public class FileHandler implements IFileHandler {
	private final String TAG = "FILE_HANDLER_ERROR";

	private File databaseFile;
	private File dir;

	public FileHandler() {
		String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath()
				+ "/apk";
		dir = new File(dirPath);
		databaseFile = new File(dirPath + "/database.txt");
	}

	@Override
	public void writeToFile(ArrayList<IBeverage> beverageList) {
		createNewFile();
		PrintWriter writer = null;
		try {
			writer = new PrintWriter(databaseFile);
		} catch (FileNotFoundException e) {
			Log.e(TAG, e.toString());
		}

		for (IBeverage beverage : beverageList) {
			writer.append(beverage.getName() + "\n" + beverage.getType() + "\n"
					+ beverage.getVolume() + "\n" + beverage.getAlc() + "\n"
					+ beverage.getPrice() + "\n" + beverage.getApk() + "\n");
		}
		writer.flush();
		writer.close();
	}

	@Override
	public String readFile() {
		StringBuilder text = new StringBuilder();

		try {
			BufferedReader bufferedReader = new BufferedReader(new FileReader(
					databaseFile));
			String line = "";

			while ((line = bufferedReader.readLine()) != null) {
				text.append(line);
				text.append("\n");
			}
		} catch (IOException e) {
			Log.e(TAG, e.toString());
		}
		return text.toString();
	}

	private void createNewFile() {
		if (dir.exists()) {
			if (dir.listFiles().length > 0) {
				for (File file : dir.listFiles()) {
					file.delete();
					Log.i("DELETE", "Deleted file: " + file.getName());
				}
			}
			dir.delete();
			Log.i("DELETE", "Deleted dir: " + dir.getName());
		}
		dir.mkdirs();
		databaseFile = new File(dir, "database.txt");
		Log.i("CREATE", "Created dir and file");
	}

	@Override
	public boolean fileExists() {
		return databaseFile.exists();
	}
}
